import React, { useState, useRef } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { authService } from '../../services/auth';
import Toast from '../../components/Toast';
import ptLogo from '../../assets/pt-logo.png';
import './Login.css';

const ForgotPassword = () => {
  const navigate = useNavigate();
  const [step, setStep] = useState(1); // 1: 发送验证码 2: 重置密码
  const [email, setEmail] = useState('');
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  // 重置密码表单
  const [form, setForm] = useState({ code: '', newPassword: '', confirmPassword: '' });
  
  // 添加引用以支持回车键功能
  const emailInputRef = useRef(null);
  const codeInputRef = useRef(null);
  const passwordInputRef = useRef(null);
  const confirmPasswordInputRef = useRef(null);

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  const handleSendCode = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      const response = await authService.requestPasswordReset(email);
      if (response.data.code === 200) {
        showToastMessage('验证码已发送至您的邮箱，请查收');
        setStep(2);
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        showToastMessage(response.data.message || '发送验证码失败');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '发送验证码失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理邮箱输入框回车事件
  const handleEmailKeyDown = (e) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleSendCode(e);
    }
  };

  // 处理重置密码表单回车事件
  const handleKeyDown = (e, field) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (field === 'code') {
        passwordInputRef.current.focus();
      } else if (field === 'newPassword') {
        confirmPasswordInputRef.current.focus();
      } else if (field === 'confirmPassword') {
        handleResetPassword(e);
      }
    }
  };

  const handleResetPassword = async (e) => {
    e.preventDefault();
    if (!form.code || !form.newPassword || !form.confirmPassword) {
      showToastMessage('请填写完整信息');
      return;
    }
    if (form.newPassword !== form.confirmPassword) {
      showToastMessage('两次输入的新密码不一致');
      return;
    }
    setLoading(true);
    try {
      const response = await authService.resetPassword({
        email,
        verificationCode: form.code,
        newPassword: form.newPassword,
      });
      if (response.data.code === 200) {
        showToastMessage('密码重置成功，请使用新密码登录');
        setTimeout(() => navigate('/login'), 1500);
      } else {
        showToastMessage(response.data.message || '重置密码失败');
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '重置密码失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-bg">
      <div className="login-card">
        <div className="login-header">
          <img src={ptLogo} alt="PT" className="pt-logo" />
          <span className="pt-title">PT种子站</span>
        </div>
        <div className="login-form">
          <h2>忘记密码</h2>
          {step === 1 && (
            <form onSubmit={handleSendCode}>
              <div className="input-group">
                <label className="input-label">注册邮箱</label>
                <input
                  className="input-box"
                  type="email"
                  value={email}
                  onChange={e => setEmail(e.target.value)}
                  onKeyDown={handleEmailKeyDown}
                  ref={emailInputRef}
                  required
                  placeholder="请输入注册邮箱"
                />
              </div>
              <button className="login-btn" type="submit" disabled={loading || countdown > 0}>
                {loading ? '发送中...' : countdown > 0 ? `${countdown}秒后重试` : '发送验证码'}
              </button>
              <div className="login-links" style={{ justifyContent: 'center' }}>
                <Link to="/login">返回登录</Link>
              </div>
            </form>
          )}
          {step === 2 && (
            <form onSubmit={handleResetPassword}>
              <div className="input-group">
                <label className="input-label">邮箱</label>
                <input
                  className="input-box"
                  type="email"
                  value={email}
                  disabled
                />
              </div>
              <div className="input-group">
                <label className="input-label">验证码</label>
                <input
                  className="input-box"
                  type="text"
                  value={form.code}
                  onChange={e => setForm(f => ({ ...f, code: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'code')}
                  ref={codeInputRef}
                  required
                  placeholder="请输入邮箱收到的验证码"
                />
              </div>
              <div className="input-group">
                <label className="input-label">新密码</label>
                <input
                  className="input-box"
                  type="password"
                  value={form.newPassword}
                  onChange={e => setForm(f => ({ ...f, newPassword: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'newPassword')}
                  ref={passwordInputRef}
                  required
                  placeholder="请输入新密码"
                />
              </div>
              <div className="input-group">
                <label className="input-label">确认新密码</label>
                <input
                  className="input-box"
                  type="password"
                  value={form.confirmPassword}
                  onChange={e => setForm(f => ({ ...f, confirmPassword: e.target.value }))}
                  onKeyDown={(e) => handleKeyDown(e, 'confirmPassword')}
                  ref={confirmPasswordInputRef}
                  required
                  placeholder="请再次输入新密码"
                />
              </div>
              <button className="login-btn" type="submit" disabled={loading}>
                {loading ? '重置中...' : '重置密码'}
              </button>
              <div className="login-links" style={{ justifyContent: 'center' }}>
                <Link to="/login">返回登录</Link>
              </div>
            </form>
          )}
        </div>
      </div>
      
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
    </div>
  );
};

export default ForgotPassword;
 